class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None

    def set(self, data):
        self.data = data

class list:
    def __init__(self):
        self.head = Node()
        self.length = 0

    def insert(self, pos, data):
        # assert pos >= 0
        # if self.length > 0:
        #     assert pos < self.length
        assert pos >= 0 and pos <= self.length

        #     find out the position to insert
        # 开始查找

        tmpPtr = self.head
        while pos > 0:
            tmpPtr = tmpPtr.next
            pos -= 1

        # insert new node
        # 找到准确位置

        newNode = Node()
        newNode.data = data
        newNode.next = tmpPtr.next
        tmpPtr.next = newNode
        self.length += 1



    def append(self, data):

        self.insert(self.length, data)

    def remove(self, pos):

        assert pos < self.length

        tmpPtr = self.head

        while pos > 0:
            tmpPtr = tmpPtr.next
            pos -= 1

        if tmpPtr.next is not None:

            delNode = tmpPtr.next
            tmpPtr.next = delNode.next
            self.length -= 1

    def foreach(self):
        tmpPte = self.head.next
        while tmpPte is not None:
            yield tmpPte.data
            tmpPte = tmpPte.next


if __name__ == '__main__':

    l = list()
    l.append(1)
    l.append(2)
    l.append(3)

    for x in l.foreach():
        print(x)


    print("Tnser new data 4")

    l.insert(1, 4)
    for x in l.foreach():
        print(x)


    print("Remove the 2th elemnt")
    l.remove(1)
    for x in l.foreach():
        print(x)

